package com.xxy.mybatispluspro.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxy.mybatispluspro.mapper.UserMapper;
import com.xxy.mybatispluspro.model.entity.User;
import com.xxy.mybatispluspro.model.request.LoginRequest;
import com.xxy.mybatispluspro.service.UserService;
import com.xxy.mybatispluspro.utils.JWTUtils;
import com.xxy.mybatispluspro.utils.JsonData;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/v1/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserMapper userMapper;

    @GetMapping(value = "list")
    public JsonData userList(){
        Map<String,Object>map = new HashMap<>();
        List<User>list=userService.list();
        return JsonData.buildSuccess(list);
    }

    @PostMapping(value = "login")
    public JsonData Login(@RequestBody LoginRequest loginRequest){
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("name", loginRequest.getUsername());
        User user = userService.getOne(queryWrapper);
        if (user!=null){
            if (loginRequest.getPassword().equals(user.getPwd())){
                String token = JWTUtils.geneJsonWebToken(user);
                Map<String,Object>map = new HashMap<>();
                map.put("token",token);
                map.put("user",user);
                return JsonData.buildSuccess(map);
            }
        }
        return JsonData.buildError("用户名或密码错误!");

    }

    @PostMapping(value = "register")
    public JsonData Register (@RequestBody Map<String,String> newer) {
        User user = new User();
        user.setName(newer.get("username"));
        user.setPwd(newer.get("password"));
        int result = userMapper.insert(user);
       if (result==1){
           String token = JWTUtils.geneJsonWebToken(user);
           Map<String,Object>map = new HashMap<>();
           map.put("token",token);
           map.put("user",user);
           return JsonData.buildSuccess(map);
       }
       else
           return JsonData.buildError("注册失败!");
    }

    @PostMapping(value = "me")
    public JsonData findUserByToken (@RequestBody Map<String,String>map){
        String token = map.get("token");
        Claims claims = JWTUtils.checkJWT(token);
        int id =(Integer) claims.get("id");
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("id",id);
        User user = userService.getOne(queryWrapper);
        return JsonData.buildSuccess(user);
    }

}
